package com.example.shardingmultdatasource.controller;

import com.example.shardingmultdatasource.config.DB;
import com.example.shardingmultdatasource.config.DBConfig;
import com.example.shardingmultdatasource.entity.Order;
import com.example.shardingmultdatasource.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    DBConfig dbConfig;


    @Autowired
    OrderService orderService;

    @RequestMapping("/insert")
    public String insert(String orderId) {
        log.info(dbConfig.getDbs().get(0).getPassword());
            String orderName = "order is " + orderId;
            Order order = new Order();
            int rId = (int) (Math.random() * 10);
//            int rId = new Random().nextInt();
            String rrId = String.format("%03d", rId);
            String tenantId = "tenant" + rrId;
            Long shardKey = Long.parseLong(Math.abs(tenantId.hashCode()) + "");
            //生成分片KEY
            order.setOrderId(orderId);
            order.setOrderName(orderName);
            order.setShardKey(shardKey);
            order.setTenantId(tenantId);
            orderService.insert(orderId,order);
        return null;
    }
}
